package one.bugu.android.demon.ui.fragment.snatch;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.juefeng.android.framework.LKUtil;
import com.juefeng.android.framework.view.annotation.LKContentView;
import com.juefeng.android.framework.view.annotation.LKInjectView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import one.bugu.android.demon.R;
import one.bugu.android.demon.bean.snatch.SnatchPeriodBean;
import one.bugu.android.demon.common.BaseHttpAsycResponceHandler;
import one.bugu.android.demon.common.MyBaseFragment;
import one.bugu.android.demon.constant.Constant;
import one.bugu.android.demon.constant.HttpConstant;
import one.bugu.android.demon.ui.activity.WebActivity;
import one.bugu.android.demon.ui.activity.snatch.SnatchDetailsActivty;
import one.bugu.android.demon.ui.adapter.snatch.SnatchRecordAdapter;
import one.bugu.android.demon.ui.refresh.SmartRefreshLayout;
import one.bugu.android.demon.ui.refresh.listener.OnRefreshListener;
import one.bugu.android.demon.ui.refresh.listener.OnRefreshLoadmoreListener;
import one.bugu.android.demon.ui.refresh.listener.RefreshLayout;
import one.bugu.android.demon.util.IntentUtils;
import one.bugu.android.demon.util.ParamUtils;
import one.bugu.android.demon.util.PreferencesUtil;

/**
 * Description SnatchRecordFragment 夺宝记录
 *
 * @author liuxin
 * @date 2018/10/27 13:49
 */
@LKContentView(R.layout.fragment_snatch_record)
public class SnatchRecordFragment extends MyBaseFragment {

    /**
     * 列表展示
     */
    @LKInjectView(R.id.lv_snatch_record)
    private ListView lv_snatch_record;

    @LKInjectView(R.id.ref_layout)
    private SmartRefreshLayout ref_layout;

    @LKInjectView(R.id.ll_empty_view)
    private View ll_empty_view;

    private int limit = 20;

    private int offset = 1;

    private static final String PAGE_TYPE = "pageType";

    private int pageType = UNDER_WAY;

    public static final int UNDER_WAY = 0;
    public static final int END = 1;
    public static final int RECORD = 2;
    /**
     * 列表数据适配器
     */
    private SnatchRecordAdapter mAdapter;

    private String token;

    private static final String TAG = "SnatchRecordFragment";

    public SnatchRecordFragment() {

    }

    /**
     * Fragment初始化
     *
     * @param param1
     * @return
     */
    public static SnatchRecordFragment newInstance(int param1) {
        SnatchRecordFragment fragment = new SnatchRecordFragment();
        Bundle args = new Bundle();
        args.putInt(PAGE_TYPE, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void initView() {
        super.initView();
        mAdapter = new SnatchRecordAdapter(getContext(), null);
        lv_snatch_record.setAdapter(mAdapter);

        ref_layout.setEnableRefresh(true);//启用刷新
        ref_layout.setEnableLoadmore(true);//启用加载
    }

    @Override
    protected void initData() {
        super.initData();
        if (getArguments() != null) {
            pageType = getArguments().getInt(PAGE_TYPE);
        }
        Log.d(TAG, "initData: " + pageType);

        token = PreferencesUtil.getInstance().getString(getContext(), Constant.TOKEN);

        getSnatchRecord();
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lv_snatch_record.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ArrayList<SnatchPeriodBean.DataBean> dataBeans = mAdapter.allData();
                if (dataBeans != null) {
                    SnatchPeriodBean.DataBean dataBean = dataBeans.get(position);
                    String h5Url = HttpConstant.ORDER_H5_URL + "?appType=android" + "&orderNo=" + dataBean.getOrderNo() + "&ordersource=2";
                    List<ParamUtils.NameValue> parList = ParamUtils.build()
                            .put(WebActivity.TITLE, "订单详情")
                            .put(WebActivity.URL, h5Url)
                            .put(WebActivity.ORDERNO, dataBean.getOrderNo())
                            .put(WebActivity.PERIODID, dataBean.getPeriodId())
                            .create();
                    IntentUtils.startAty(getContext(), WebActivity.class, parList);
                }
            }
        });
        ref_layout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                offset++;
                getSnatchRecord();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //刷新数据
                offset = 1;
                ref_layout.setEnableLoadmore(true);
                getSnatchRecord();
            }
        });
    }

    /**
     * 显示缺省页
     */
    private void showEmptyView() {
        boolean status = mAdapter == null || mAdapter.allData() == null || mAdapter.allData().size() == 0;
        ll_empty_view.setVisibility(status ? View.VISIBLE : View.GONE);
        ref_layout.setVisibility(status ? View.GONE : View.VISIBLE);
    }

    private void getSnatchRecord(int status, int winStatus) {
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("limit", String.valueOf(limit));
        map.put("offset", String.valueOf(offset));
        if (winStatus == 0) {
            map.put("status", String.valueOf(status));
        } else {
            map.put("winStatus", String.valueOf(winStatus));
            map.put("status", "20");
        }
        LKUtil.getHttpManager().postBody(HttpConstant.GET_SNATCH_PERIOD_RECORD, map, getSnatchPeriodHander);
    }

    @SuppressLint("HandlerLeak")
    private BaseHttpAsycResponceHandler getSnatchPeriodHander =
            new BaseHttpAsycResponceHandler<SnatchPeriodBean>() {
                @Override
                public void onSuccess(SnatchPeriodBean snatchPeriodBeans) {
                    super.onSuccess(snatchPeriodBeans);
                    ref_layout.finishRefresh();
                    ref_layout.finishLoadmore();
                    if (snatchPeriodBeans != null) {
                        List<SnatchPeriodBean.DataBean> data = snatchPeriodBeans.getData();
                        if (null != data) {
                            if (offset == 1) {
                                mAdapter.clear();
                            }
                            mAdapter.addAll((ArrayList<SnatchPeriodBean.DataBean>) data);
                            ref_layout.setEnableLoadmore(!(data.size() < limit));
                        } else {
                            ref_layout.setEnableLoadmore(false);
                        }
                    } else {
                        ref_layout.setEnableLoadmore(false);
                    }

                    showEmptyView();
                }

                @Override
                public void onFailed(int code, String message) {
                    super.onFailed(code, message);
                    ref_layout.finishRefresh();
                    ref_layout.finishLoadmore();
                    if (offset > 1) offset--;
                    showEmptyView();
                }

                @Override
                public void onError() {
                    super.onError();
                    ref_layout.finishRefresh();
                    ref_layout.finishLoadmore();
                    if (offset > 1) offset--;
                    showEmptyView();
                }
            };

    /**
     * 获取夺宝记录
     */
    private void getSnatchRecord() {
        if (pageType == UNDER_WAY) {
            getSnatchRecord(10, 0);
        } else if (pageType == END) {
            getSnatchRecord(20, 0);
        } else if (pageType == RECORD) {
            getSnatchRecord(0, 30);
        }
    }
}
